package httpsvr

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"time"

	"gitee.com/daledi/public/options"
	"gitee.com/daledi/public/vmap"
	"github.com/pkg/errors"
)

type HttpTest struct {
	Router   *Router
	OPT      options.GlobalOPT
	IsSimple bool
	Valid    bool
}

func NewTest(conf string) HttpTest {
	ht := HttpTest{
		OPT:      options.GOPT(),
		Router:   NewRouter("", nil),
		IsSimple: true,
		Valid:    true,
	}
	var err error
	if ht.OPT, err = options.ReadConfig(conf); err != nil {
		log.Fatalf("Cant read test.conf: %v\n", err)
	}
	// router := httpsvr.NewRouter("", nil)
	ht.Router.Prefix = ht.OPT.Prefix
	ht.Router.ErrLog = ht.OPT.ErrLog
	ht.Router.ResponseHandler = func(ctx *Context) {
		if ctx.Response == nil {
			ctx.Response = 9999
		}
		//econf.LogDebug("[Defer] Response: %v\n", ctx.Response)
		fmt.Printf("耗时：%s\n", time.Since(ctx.Begin).String())
		// switch v := ctx.Response.(type) {
		// case int:
		// 	msg := NewRespMsg(v)
		// 	ctx.Writer.Header().Set("X-Code", strconv.Itoa(v))
		// 	ctx.Response = msg.Bytes()
		// 	ctx.ContextType = TypeJson
		// }
	}

	ht.Router.PanicHandler = func(ctx *Context) {
		if err := recover(); err != nil {
			gConf := ctx.Keys["conf"].(options.GlobalOPT)
			httprequest, _ := httputil.DumpRequest(ctx.Req, false)
			gConf.ErrLog.Printf("[Recovery] Request: %s\n", string(httprequest))
			gConf.ErrLog.Printf("[Recovery] Error: %s\n", fmt.Sprintf("%+v", errors.Errorf("%v", err)))
			ctx.Writer.WriteHeader(http.StatusInternalServerError)
		}
	}
	return ht
}

func (ht HttpTest) HttpApiTest(req *http.Request) {
	res := httptest.NewRecorder()
	// req, _ := http.NewRequest("PUT", "/gfc/globalsumdata/v2", bytes.NewReader(data))
	// req.Header.Set("X-Token", "test")
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Real-IP", "127.0.0.1")
	ht.Router.ServeHTTP(res, req)
	fmt.Printf("%s %s response:\n", req.Method, req.URL.Path)
	// formatOut(res.Body, isSimple)
	r := res.Result()
	fmt.Printf("Status: %s\n", r.Status)
	var tt vmap.V
	if err := json.Unmarshal(res.Body.Bytes(), &tt); err != nil {
		fmt.Printf("err: %v\n", err)
	}
	if ht.IsSimple {
		fmt.Printf("%v: %s\n", tt["code"], tt.VString("message"))
		return
	}
	cc, _ := json.MarshalIndent(tt, "", "  ")
	fmt.Printf("Body: %s\n", string(cc))
}
